<?php
// +----------------------------------------------------------------------
// | 敦煌网商品发布控制器
// +----------------------------------------------------------------------

namespace app\Api\controller;

use app\BaseController;
use app\Api\system\ItemAddService;
use think\Request;
use think\Response;

class ItemAdd extends BaseController
{
    /**
     * 发布商品到敦煌网
     * @param Request $request
     * @return Response
     */
    public function add(Request $request)
    {
        try {
            // 获取请求参数
            $params = $request->param();
            
            // 获取店铺ID
            $shopId = $params['shop_id'] ?? 1;
            
            // 从数据库获取访问令牌
            $accessToken = $this->getTokenByCode($shopId);
            if (empty($accessToken)) {
                return $this->error('访问令牌不能为空，请先进行授权');
            }
            
            // 记录请求开始
            $this->logRequest($params);
            
            // 调用服务发布商品
            $result = ItemAddService::addItem($accessToken, $params);
            
            // 返回结果
            if ($result['success']) {
                return $this->success($result['message'], $result['data']);
            } else {
                return $this->error($result['message'], $result['data']);
            }
            
        } catch (\Exception $e) {
            error_log('[ItemAdd Controller] Exception: ' . $e->getMessage());
            return $this->error('系统异常: ' . $e->getMessage());
        }
     }
     /**
     * 测试API连接
     * @param Request $request
     * @return Response
     */
    public function testConnection(Request $request)
    {
        try {
            // 获取店铺ID
            $shopId = $request->param('shop_id', 1);
            
            // 从数据库获取访问令牌
            $accessToken = $this->getTokenByCode($shopId);
            if (empty($accessToken)) {
                return $this->error('访问令牌不能为空，请先进行授权');
            }
            
            $result = ItemAddService::testApiConnection($accessToken);
            
            if ($result['success']) {
                return $this->success($result['message'], $result);
            } else {
                return $this->error($result['message'], $result);
            }
            
        } catch (\Exception $e) {
            return $this->error('测试连接异常: ' . $e->getMessage());
        }
    }
        
    /**
     * 获取默认配置数据
     * @return Response
     */
    public function getDefaultConfig()
    {
        try {
            $config = ItemAddService::getDefaultConfig();
            return $this->success('获取默认配置成功', $config);
        } catch (\Exception $e) {
            return $this->error('获取默认配置失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 批量发布商品
     * @param Request $request
     * @return Response
     */
    public function batchAdd(Request $request)
    {
        try {
            $params = $request->param();
            // 获取店铺ID
            $shopId = $params['shop_id'] ?? 1;
            $items = $params['items'] ?? [];
            
            // 从数据库获取访问令牌
            $accessToken = $this->getTokenByCode($shopId);
            if (empty($accessToken)) {
                return $this->error('访问令牌不能为空，请先进行授权');
            }
            
            if (empty($items) || !is_array($items)) {
                return $this->error('商品列表不能为空');
            }
            
            $results = [];
            $successCount = 0;
            $failCount = 0;
            
            foreach ($items as $index => $item) {
                try {
                    $result = ItemAddService::addItem($accessToken, $item);
                    $results[] = [
                        'index' => $index,
                        'success' => $result['success'],
                        'message' => $result['message'],
                        'data' => $result['data'] ?? null
                    ];
                    
                    if ($result['success']) {
                        $successCount++;
                    } else {
                        $failCount++;
                    }
                    
                    // 避免请求过于频繁
                    if ($index < count($items) - 1) {
                        sleep(1);
                    }
                    
                } catch (\Exception $e) {
                    $results[] = [
                        'index' => $index,
                        'success' => false,
                        'message' => '发布异常: ' . $e->getMessage(),
                        'data' => null
                    ];
                    $failCount++;
                }
            }
            
            return $this->success('批量发布完成', [
                'total' => count($items),
                'success_count' => $successCount,
                'fail_count' => $failCount,
                'results' => $results
            ]);
            
        } catch (\Exception $e) {
            return $this->error('批量发布异常: ' . $e->getMessage());
        }
    }
    
    /**
     * 验证商品数据
     * @param Request $request
     * @return Response
     */
    public function validate(Request $request)
    {
        try {
            $params = $request->param();
            
            // 移除access_token，只验证商品数据
            unset($params['access_token']);
            
            // 使用服务类的验证方法
            $validation = $this->validateItemData($params);
            
            if ($validation === true) {
                return $this->success('数据验证通过', [
                    'valid' => true,
                    'message' => '所有必需参数格式正确'
                ]);
            } else {
                return $this->error('数据验证失败', [
                    'valid' => false,
                    'message' => $validation
                ]);
            }
            
        } catch (\Exception $e) {
            return $this->error('验证异常: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取商品发布状态
     * @param Request $request
     * @return Response
     */
    public function getStatus(Request $request)
    {
        try {
            $itemCode = $request->param('item_code', '');
            
            if (empty($itemCode)) {
                return $this->error('商品编码不能为空');
            }
            
            // 这里可以添加查询商品状态的逻辑
            // 目前返回基本信息
            return $this->success('获取状态成功', [
                'item_code' => $itemCode,
                'status' => 'published',
                'message' => '商品已发布'
            ]);
            
        } catch (\Exception $e) {
            return $this->error('获取状态异常: ' . $e->getMessage());
        }
    }
    
    /**
     * 记录请求日志
     * @param array $params
     */
    private function logRequest($params)
    {
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'ip' => request()->ip(),
            'user_agent' => request()->header('user-agent'),
            'params_count' => count($params),
            'has_access_token' => !empty($params['access_token'])
        ];
        
        // 脱敏处理
        if (isset($params['access_token'])) {
            $logData['access_token_preview'] = substr($params['access_token'], 0, 10) . '...';
        }
        
        error_log('[ItemAdd Request] ' . json_encode($logData, JSON_UNESCAPED_UNICODE));
    }
    
    /**
     * 验证商品数据
     * @param array $params
     * @return bool|string
     */
    private function validateItemData($params)
    {
        // 必需参数列表
        $requiredParams = [
            'catePubId' => '发布类目ID',
            'shippingModelId' => '运费模板ID', 
            'afterSaleTemplateId' => '售后模板ID',
            'itemImgList' => '产品图片列表',
            'itemBase' => '产品基础信息',
            'itemSkuList' => '产品SKU列表',
            'itemSaleSetting' => '产品销售设置',
            'itemPackage' => '产品包装信息'
        ];
        
        foreach ($requiredParams as $param => $name) {
            if (!isset($params[$param]) || empty($params[$param])) {
                return "缺少必需参数: {$name}({$param})";
            }
        }
        
        // 验证JSON格式参数
        $jsonParams = ['itemImgList', 'itemBase', 'itemSkuList', 'itemSaleSetting', 'itemPackage'];
        foreach ($jsonParams as $param) {
            if (isset($params[$param]) && is_string($params[$param])) {
                $decoded = json_decode($params[$param], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    return "参数 {$param} JSON格式错误: " . json_last_error_msg();
                }
            }
        }
        
        // 验证类目ID格式
        if (!preg_match('/^\d{9,12}$/', $params['catePubId'])) {
            return '类目ID格式不正确，应为9-12位数字字符串';
        }
        
        return true;
    }
    
    /**
     * 成功响应
     * @param string $message
     * @param mixed $data
     * @return Response
     */
    private function success($message = '操作成功', $data = null)
    {
        $response = [
            'code' => 200,
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
        
        return json($response);
    }
    
    /**
     * 错误响应
     * @param string $message
     * @param mixed $data
     * @return Response
     */
    private function error($message = '操作失败', $data = null)
    {
        $response = [
            'code' => 400,
            'success' => false,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
        
        return json($response);
    }
}